<template>
	<div class="workflow-record-container">
		<div class="header">
			<el-button type="primary" :class="processRecordsClone.length === 0 ? 'gray-btn' : 'download-btn'" @click="onClickDownload" :disabled="processRecordsClone.length === 0 ? true : false"
				>下载</el-button
			>
			<div class="search">
				<el-select v-model="agentName" placeholder="所有坐席" @change="searchRecordByName">
					<el-option v-for="item in options" :key="item" :label="item.label" :value="item.value"> </el-option>
				</el-select>
				<el-input placeholder="请输入搜索内容" v-model="searchKeyWord" @keyup.enter.native="searchContent">
					<el-button slot="append" icon="el-icon-search" @click="searchContent"></el-button>
				</el-input>
			</div>
		</div>
		<div class="workflow-item-wrapper">
			<div v-for="(node, index) in processRecordsClone" :key="node.id">
				<WorkflowItem :index="index + 1" :node="node" />
			</div>
		</div>
		<RichText
			v-if="showRichText"
			:dialogVisible="showRichText"
			:richText="richText"
			@close="
				() => {
					showRichText = false;
				}
			"
		/>
		<ViewFormDeatil
			v-if="showForm"
			:dialogVisible="showForm"
			:formId="formId"
			@close="
				() => {
					showForm = false;
				}
			"
		/>
	</div>
</template>

<script>
import { getWorkflowRecord } from '@/api/api.js';
import _ from 'lodash';
import WorkflowItem from './WorkflowItem.vue';
import { saveAs } from 'file-saver';
import { parseWorkFlow } from '../../utils/parse-workflow-node';
export default {
	components: { WorkflowItem },
	props: {},
	data() {
		return {
			options: [],
			searchKeyWord: '',
			agentName: '所有坐席',
			processRecords: [],
			processRecordsClone: [],
			sessionId: this.$route.query.sessionId,
			// 富文本
			showRichText: false,
			richText: '',
			// 表单
			showForm: false,
			formId: ''
		};
	},
	mounted() {
		this.getWorkflowRecordList();
	},
	methods: {
		// 初始化获取补录详情数据
		getWorkflowRecordList() {
			getWorkflowRecord(this.sessionId)
				.then(res => {
					if (res.data) {
						this.processRecords = [];
						const processRecords = res.data;
						processRecords.map(item => {
							item.startedAt = item.startedAt ? this.$moment(item.startedAt).format('YYYY-MM-DD HH:mm:ss.SSS') : '-';
							item.closedAt = item.closedAt ? this.$moment(item.closedAt).format('YYYY-MM-DD HH:mm:ss.SSS') : '-';
							item.duration = this.formatDuration(item.duration / 1000);
							parseWorkFlow(item);
						});
						this.processRecords = [...processRecords];
						this.getSessionAllAgents(this.processRecords);
						this.processRecordsClone = _.cloneDeep(this.processRecords);
					} else {
						console.error('获取工作流数据', res.data);
						this.$message.warning('获取工作流数据失败');
					}
				})
				.catch(err => {
					console.error('获取工作流数据', err);
					this.$message.warning('获取工作流数据失败');
				})
				.finally(() => {
					this.$Spin.hide();
				});
		},
		formatDuration(duration) {
			let hours = Math.floor(duration / 3600);
			let minutes = Math.floor((duration - hours * 3600) / 60);
			let seconds = (duration - hours * 3600 - minutes * 60).toFixed(3);
			// console.log(parseInt(seconds),'seconds')
			if (hours < 10) {
				hours = '0' + hours;
			}
			if (minutes < 10) {
				minutes = '0' + minutes;
			}
			if (seconds < 10) {
				seconds = '0' + seconds;
			}
			return hours + ':' + minutes + ':' + seconds;
		},
		getSessionAllAgents(data) {
			let agents = [
				{
					label: '所有坐席',
					value: '所有坐席'
				}
			];
			if (data) {
				data.map(item => {
					if (item.agentUsername) {
						agents.push({
							label: item.agentUsername,
							value: item.agentUsername
						});
					}
				});
			}
			console.log(agents);
			this.options = _.uniqWith(agents, _.isEqual);
		},
		// 下载工作流记录
		onClickDownload() {
			const nodes = document.querySelectorAll('div.workflow-item-wrapper');
			const list = [].slice.call(nodes);
			const innertext = list
				.map(function (e) {
					return e.innerText;
				})
				.join('\n');
			// console.warn('innertext : ', innertext);
			if (innertext) {
				const blob = new Blob([innertext], { type: 'text/plain;charset=utf-8' });
				const fileName = this.sessionId + '工作流' + '.txt';
				saveAs(blob, fileName);
			} else {
				this.$message.error('下载工作流记录失败！');
			}
		},
		// 关键字搜索
		async searchContent() {
			if (this.agentName) {
				if (this.agentName === '所有坐席') {
					this.processRecordsClone = _.cloneDeep(this.processRecords);
				} else {
					this.processRecordsClone = _.cloneDeep(this.processRecords);
					this.processRecordsClone = this.processRecordsClone.filter(item => item.agentUsername === this.agentName);
				}
			}
			this.searchKeyWord = this.searchKeyWord.trim();
			if (!this.searchKeyWord) {
				return;
			}
			let result = [];
			this.processRecordsClone.map(node => {
				if (
					node.agentUsername?.includes(this.searchKeyWord) ||
					node.modTitle?.includes(this.searchKeyWord) ||
					node.startedAt?.includes(this.searchKeyWord) ||
					node.closedAt?.includes(this.searchKeyWord) ||
					node.duration?.includes(this.searchKeyWord) ||
					node.result?.includes(this.searchKeyWord) ||
					node.request?.includes(this.searchKeyWord) ||
					node.requestName?.includes(this.searchKeyWord) ||
					node.requestUrl?.includes(this.searchKeyWord) ||
					node.answer?.includes(this.searchKeyWord) ||
					node.answerKey?.includes(this.searchKeyWord) ||
					node.answerName?.includes(this.searchKeyWord) ||
					node.answerUrl?.includes(this.searchKeyWord) ||
					node.answerAddress?.includes(this.searchKeyWord) ||
					node.answerCode?.includes(this.searchKeyWord) ||
					node.answerListenindSpeech?.includes(this.searchKeyWord) ||
					node.answerText?.includes(this.searchKeyWord) ||
					node.typeOfCollectedResults?.includes(this.searchKeyWord) ||
					node.summary?.includes(this.searchKeyWord) ||
					node.variables?.includes(this.searchKeyWord) ||
					node.requestAgentName?.includes(this.searchKeyWord) ||
					node.requestReceiveMediaType?.includes(this.searchKeyWord) ||
					node.requestMicrophoneStatus?.includes(this.searchKeyWord)
				) {
					result.push(node);
				}
			});
			result.map(node => {
				node.agentUsername = this.brightKeyword(node.agentUsername);
				node.modTitle = this.brightKeyword(node.modTitle);
				node.startedAt = this.brightKeyword(node.startedAt);
				node.closedAt = this.brightKeyword(node.closedAt);
				node.duration = this.brightKeyword(node.duration);
				node.result = this.brightKeyword(node.result);
				node.request = this.brightKeyword(node.request);
				node.requestName = this.brightKeyword(node.requestName);
				node.requestUrl = this.brightKeyword(node.requestUrl);
				node.answer = this.brightKeyword(node.answer);
				node.answerKey = this.brightKeyword(node.answerKey);
				node.answerName = this.brightKeyword(node.answerName);
				node.answerUrl = this.brightKeyword(node.answerUrl);
				node.answerAddress = this.brightKeyword(node.answerAddress);
				node.answerCode = this.brightKeyword(node.answerCode);
				node.answerListenindSpeech = this.brightKeyword(node.answerListenindSpeech);
				node.answerText = this.brightKeyword(node.answerText);
				node.typeOfCollectedResults = this.brightKeyword(node.typeOfCollectedResults);
				node.summary = this.brightKeyword(node.summary);
				node.variables = this.brightKeyword(node.variables);
				node.requestAgentName = this.brightKeyword(node.requestAgentName);
				node.requestReceiveMediaType = this.brightKeyword(node.requestReceiveMediaType);
				node.requestMicrophoneStatus = this.brightKeyword(node.requestMicrophoneStatus);
			});
			this.processRecordsClone = result;
		},
		brightKeyword(val) {
			if (!val) {
				return val;
			}
			let keyword = this.searchKeyWord; //获取输入框输入的内容
			console.log(val.indexOf(keyword));
			if (val.indexOf(keyword) !== -1) {
				//如果包含的话，就把这个字段中的那一部分进行替换成html字符
				const htmlFragment = `<span style="color: #6384FE; background: #F0F2F3;">${keyword}</span>`;
				return val.replace(eval('/' + keyword + '/g'), htmlFragment);
			}
			// console.log('brightKeyword', keyword);
			// console.log('val:', val);
			return val;
		},
		async searchRecordByName() {
			this.searchContent();
		}
	}
};
</script>

<style lang="less" scoped>
.workflow-record-container {
	padding: 20px;
	.el-input {
		width: 370px;
	}
	.el-select {
		width: 140px;
		margin-right: 20px;
	}
	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		.download-btn {
			background: #6384fe;
			border-radius: 4px;
			color: #fff;
		}
		.gray-btn {
			background: #e7e7e7;
			border: none;
			color: #fff;
		}
	}
	.search {
		color: #666;
	}
	.keyword {
		background-color: #606266;
		color: #6384fe;
	}
}
</style>
<style lang="less">
.workflow-record-container {
	.search {
		.el-input__icon {
			line-height: 100%;
		}
	}
	.workflow-item-wrapper {
		margin-top: 10px;
	}
}
</style>
